angular.module('GiveStock')

.controller('GiveStock.HomeCtrl', ['$scope', '$state', '$filter','GiveStockHomeService', 'User', 'Device', 'imanDialog', '$ionicLoading','$stateParams','Socket','$interval', function($scope, $state, $filter, GiveStockHomeService, User, Device, imanDialog, $ionicLoading,$stateParams,Socket,$interval) {
    
    var departmentId = "";
    $scope.data = {};
    var barcodeMasters = [];
    var listData = [];
    
    var userName = User.get("Name");
    var userId = User.get("_id");//用户id
    var wareHouse;
    var wareHouseId ;//待转区id

    var a=0;//分页页码数
    $scope.aTemp = 1;
    var pageData = {};//分业后的数据
    var timer;//定时器

    $scope.homeData = {
        transferAreaName: "", //待转区名字 
        userName: User.get("Name"),
        dateNow: Date.now(),
        houses:[],//存储仓库数据
        selectHouse:''//选中的house
    };


    function onkeydown(event) {
        var keyCode = event.keyCode;
        
        if (keyCode === 13) { // 确认
            $state.go('House');
        }
    }
    $scope.$on('$ionicView.afterEnter', function () {
        if(Device.isTV()){
            
            angular.element(document).keydown(onkeydown);
        }
        Socket.connect();
        wareHouse = angular.fromJson(window.localStorage.getItem("wareHouse"));
        if(wareHouse){
            initData(wareHouse);
        }
    });
    $scope.$on('$ionicView.beforeLeave', function () {
        if(Device.isTV()){
       
            angular.element(document).off('keydown', onkeydown);
        } 
        
        if(wareHouseId){
            Socket.off(wareHouseId.toString(), onSocket);
         } 
         Socket.disconnect();    
    });
  
    $scope.data.gridOptions = {
        //enableRefresh: true,

        columnDefs: [{
                col: 'ItemMasterCode',
                name: '型号'
            }, {
                col: 'DescSeg1',
                name: '尺寸'
            }, {
                col: 'DescSeg2',
                name: '外观'
            }, {
                col: 'DemandDepartment',
                name: '需求部门'
            }, {
                col: 'DemandQty',
                name: '下游要货'
            }, {
                col: 'NeedQty',
                name: '待备货量',
                cls: 'givestock-column-red'
            }, {
                col: 'RcvQty',
                name: '超市库存',
                cls: 'givestock-column-green'
            }, {
                col: 'TotalStockQty',
                name: '已备货量'
            }, {
                col: 'TotalReceiveQty',
                name: '接收数量'
            }],
        data: []
    };

    $scope.gethouses = function() {
        $state.go('House');
    };


    //对批次物料条件模糊查询
    $scope.search = function(query) {

        if (query === "") {
            $scope.data.gridOptions.data = listData;
        }
        if (query !== "") {
            var nPosDescSeg1;
            var nPosDescSeg2;
            var nPosItem;
            var nPosDepartment;
            $scope.data.gridOptions.data = [];

            for (var i in listData) {
                var DescSeg1 = listData[i].DescSeg1;
                var DescSeg2 = listData[i].DescSeg2;
                var itemMasterCode = listData[i].ItemMasterCode;
                var Department = listData[i].DemandDepartment;
                nPosDescSeg1 = find(query, DescSeg1);
                nPosDescSeg2 = find(query, DescSeg2);
                nPosItem = find(query, itemMasterCode);
                nPosDepartment = find(query, Department);
                //nPos=sTxt.indexOf(sFind);   
                if (nPosDescSeg1 >= 0 || nPosDescSeg2 >= 0 || nPosItem >= 0 || nPosDepartment>=0) {
                   $scope.data.gridOptions.data.push(listData[i]);
                }
            }
            if ($scope.data.gridOptions.data.length === 0) {
                imanDialog.toastBottom("未找到相关信息");     
            }
        }
    };

    $scope.doRefresh = function(operate, item) {
        imanDialog.showLoading();
        GiveStockHomeService.queryGiveStockData(wareHouseId,departmentId).then(function(data){
           
           $scope.$broadcast('scroll.refreshComplete');
           imanDialog.hideLoading();
           initKanbanData(data);
           
        },function(error){
           $scope.$broadcast('scroll.refreshComplete');
           $scope.data.gridOptions.data = [];
           imanDialog.hideLoading();
        });
        
    };

  

    function initKanbanData(data){
        if(data.length>0){
            //找到不同的部门
            var Departments = [data[0].DemandDepartment];
            //待备货量>0 的
            var NeedQtys = [];
            var NeedQtyTemps = [];
            //待备货量=0 的
            var NeedQty0s = [];
            var NeedQty0Temps = [];
            for (var i = 0; i < data.length; i++) {
                var repeat = false;
                for (var j = 0; j < Departments.length; j++) {
                    if (data[i].DemandDepartment === Departments[j]) {
                        repeat = true;
                        break;
                    }
                }
                if (!repeat) {
                    Departments.push(data[i].DemandDepartment);
                }
                if(data[i].NeedQty===0){
                    NeedQty0s.push(data[i]);
                }
                else{
                    NeedQtys.push(data[i]);
                }
            }

            for (var a = 0; a < Departments.length; a++) {
                for (var b = 0; b < NeedQtys.length; b++) {
                    if(NeedQtys[b].DemandDepartment===Departments[a]){
                       NeedQtyTemps.push(NeedQtys[b]);
                    }
                }   
            }
            for (var c = 0; c < Departments.length; c++) {
                for (var d = 0; d < NeedQty0s.length; d++) {
                    if(NeedQty0s[d].DemandDepartment===Departments[c]){ 
                       NeedQty0Temps.push(NeedQty0s[d]);
                    }
                }   
            }

            data = NeedQtyTemps.concat(NeedQty0Temps);
        }
        
        $scope.data.gridOptions.data = data;
        cutPage();
        listData = $scope.data.gridOptions.data;
    }
    
    function cutPage(){
        
        if($scope.data.gridOptions.data.length>10){
            for (var i = 0; i < $scope.data.gridOptions.data.length; i++) {
                if(i%10===0){
                    a++;
                }
                if (pageData[a]) {
                    pageData[a].push($scope.data.gridOptions.data[i]);   
                } else {
                    pageData[a] = [$scope.data.gridOptions.data[i]];
                } 
                   
            }
            $scope.data.gridOptions.data = pageData[1];
            // timer = window.setInterval(updatePage,5000);
            timer = $interval(function(){
                if($scope.aTemp<a){
                  $scope.aTemp++; 
                }else{
                  $scope.aTemp=1; 
                }
                
                $scope.data.gridOptions.data = angular.copy(pageData[$scope.aTemp]);
                
                // $scope.$apply();
            },5000);
        } 

    }

    function initData(wareHouse) {
        $scope.homeData.selectHouse = wareHouse.Name;
        wareHouseId = wareHouse._id;
        Socket.on(wareHouseId.toString(), onSocket);
        window.localStorage.setItem("wareHouse", angular.toJson(wareHouse));
        imanDialog.showLoading();
        
        GiveStockHomeService.queryGiveStockData(wareHouseId,departmentId).then(function(data){
           imanDialog.hideLoading();
           
           initKanbanData(data);
           
           
        },function(error){
           
           $scope.data.gridOptions.data = [];
           imanDialog.hideLoading();
           
        });
        
    }

    function onSocket () {
        // imanDialog.toastBottom("on");
        imanDialog.showLoading();
        GiveStockHomeService.queryGiveStockData(wareHouseId,departmentId).then(function(data){
           imanDialog.hideLoading();
           
           initKanbanData(data);
           
        },function(error){
           
           $scope.data.gridOptions.data = [];
           imanDialog.hideLoading();
           
        });
    }
    
    

    function find(sFind, sObj) {
        var nSize = sFind.length;
        var nLen = sObj.length;
        var sCompare;

        if (nSize <= nLen) {
            for (var i = 0; i <= nLen - nSize + 1; i++) {
                sCompare = sObj.substring(i, i + nSize);
                if (sCompare === sFind) {
                    return i;
                }
            }
        }
        return -1;
    }

    
}]);